import {_get, _config} from "@/js/s94_tool.js";
import s94Mjs from "s94-js";
import {S94Model} from "@/js/S94Model.js";

function to_string(v){
    switch (typeof v) {
        case 'boolean': {v = v ? 1 : 0;} break;
        case 'object': {v = JSON.stringify(v);} break;
    }
    return s94Mjs.to_string(v);
}

class S94Compute{
    constructor(info){
        this.info = info;
        this.input = _get();
    }

    compute(code) {
        code = s94Mjs.to_string(code);
        if (!code) return "";
        if (!/^\w+\([\s\S]*\)$/.test(code)) throw `计算代码只能为已存在函数，计算代码：${code}`;
        let run_code = 'return ' + code.replace('$this->', 'this.').replace(/\w+\(/, 'this.$&');
        let run_func = new Function(run_code);
        let res = run_func.call(this);
        return res;
    }
    outString(output) {
        output = s94Mjs.to_string(output);
        let count = 1;
        while (count > 0){
            count = 0;
            output = output.replace(/`([^`]+)`/, (m0, m1)=>{
                count++;
                let res = to_string(this.compute(m1));
                return res;
            });
        }
        return output;
    }

    // ---------------------------------- 以下为处理方法 -----------------------------

    get(data, key, def){
        return s94Mjs.map(data, key, def);
    }
    get_true(data, ...keys){
        let res = '';
        keys.some(key=>{
            res = s94Mjs.map(data, key);
            return !!res;
        })
        return res;
    }
    list_get(list, key, index_key){
        let res = [];
        Object.values(list).forEach(data=>{
            let v = s94Mjs.map(data, key);
            let k = index_key ? s94Mjs.map(data, index_key) : '';
            if (k){
                res[k] = v;
            }else {
                res.push(v);
            }
        })
        return res;
    }
    list_get_true(list, ...keys){
        let res = [];
        Object.values(list).forEach(data=>{
            let v = this.get_true(data, ...keys);
            res.push(v);
        })
        return res;
    }
    join(list, separator=','){
        return Object.values(list).join(separator);
    }

    this_user(key='id'){
        return _config(`this_user.${key}`);
    }
    this_admin(key='id'){
        return _config(`this_admin.${key}`);
    }
    this_tenant(key='id'){
        return _config(`this_tenant.${key}`);
    }
}


export default S94Compute;


